package com.dxy.lc.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxy.lc.enums.RoomUserOpt;
import com.dxy.lc.mapper.RoomUserMapper;
import com.dxy.lc.model.entity.RoomUser;
import com.dxy.lc.service.SessionBindService;
import com.dxy.lc.socketio.ISessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class SessionBindServiceImpl implements SessionBindService {

    @Autowired
    private ISessionService sessionService;
    @Autowired
    private RoomUserMapper roomUserMapper;

    /**
     * 在socket连接的时候绑定session
     * @param userId
     * @param sessionId
     */
    @Override
    public void bindSessionOnConnect(Integer userId, String sessionId) {
        // 绑定userId和sessionId
        sessionService.setUserBind(userId.toString(), sessionId);

        // 绑定roomId和sessionId
        List<RoomUser> roomUsers = roomUserMapper.selectList(new LambdaQueryWrapper<RoomUser>()
                .eq(RoomUser::getUserId, userId));
        roomUsers.forEach(ru -> {
            sessionService.setRoomBind(ru.getRoomId().toString(), sessionId);
        });
    }

    /**
     * 在加入/踢出聊天室时绑定session
     * @param editType 1-加入聊天室，2-踢出聊天室
     * @param roomId
     * @param userIds
     */
    @Override
    public void bindSessionOnEditRoom(RoomUserOpt editType, Integer roomId, Integer... userIds) {
        for (Integer userId : userIds) {
            // 获取userId绑定的sessionId集合
            Set<String> sessionIds = sessionService.getUserBind(userId.toString());

            if (CollUtil.isEmpty(sessionIds)){
                continue;
            }

            // 加入聊天室，设置绑定
            if (editType.equals(RoomUserOpt.JOIN)){
                sessionIds.forEach(sessionId -> sessionService.setRoomBind(roomId.toString(), sessionId));
            }

            // 踢出聊天室，移除绑定
            if (editType.equals(RoomUserOpt.REMOVE)){
                sessionIds.forEach(sessionId -> sessionService.removeRoomBind(roomId.toString(), sessionId));
            }
        }
    }
}
